<template>
  <div>
    <el-row>
      <el-card class="box-card" shadow="never" body-style="padding:10px;">
        <div slot="header" class="clearfix">
          <el-row :gutter="20" class="wrapperSon" style="margin-top:10px;">
            <el-col :span="3">订单总览</el-col>
            <el-col :span="21" class="wrapperSon" style="font-size: 13px;">
              <el-button type="primary" icon="el-icon-open" @click="changeProduceLine">
                切换产线
              </el-button>
              <span>指定排产月份:</span>
              <el-select
                v-model="queryConditions.produceYear"
                placeholder="请选择年份"
                @change="handleYearChange"
              >
                <el-option
                  v-for="itm in this.lstYears"
                  :label="itm.label"
                  :value="itm.value"
                  :key="itm.value"
                >
                </el-option>
              </el-select>
              <el-select
                v-model="queryConditions.produceMonth"
                placeholder="请选择月份"
                @change="handleMonthChange"
              >
                <el-option
                  v-for="itm in this.lstMonths"
                  :label="itm.label"
                  :value="itm.value"
                  :key="itm.value"
                ></el-option>
              </el-select>
              <el-button-group>
                <el-button type="primary" @click="allocateResource" icon="el-icon-set-up"
                  >资源配置</el-button
                >
                <el-button type="primary"  icon="el-icon-edit">修改计划</el-button>
                <el-button type="primary"  icon="el-icon-search">历史节点查看</el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </div>
        <div >
          <el-row :gutter="20" class="app-container">
            <el-col :span="4">包含工序</el-col>
            <el-col :span="20" class="wrapperSon" style="font-size:13px;">
              <el-badge
                class="item"
                v-for="(itm,
                index) in this.queryConditions.lstProcedures.filter(
                  v => v.id > 0
                )"
                :value="itm.usedDeviceLoadFactor"
                :key="itm.id"
              >
                <el-button
                  :type="getBadgeButtonColor(index, itm)"
                  size="medium"
                  round
                >
                  {{ itm.procedureName }}</el-button
                >
              </el-badge>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <schedulemonthdetailson
              :produceLineId="this.queryConditions.currentProduceLineId"
              @changeTotalPlanAmount="changeTotalPlanAmount"
            ></schedulemonthdetailson>
          </el-row>
          <el-row :gutter="20"> 
            <div id="chartProduce" class="main_container"></div>
          </el-row>
        </div>
      </el-card>
    </el-row>
    <producelinedetailselectdlg
      :dialogVisible="this.dialogProduceLineVisible"
      @hideDlg="hideProduceLineDlg"
      @refreshTbl="refreshProduceLine"
    ></producelinedetailselectdlg>
    <producelineresourcesetdlg
      :dialogVisible="this.resourceSetDlgVisible"
      :input="{ ...queryConditions }"
      @hideResourceDlg="hideResourceDlg"
      @updateFactor="updateFactor"
    ></producelineresourcesetdlg>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import producelinedetailselectdlg from "@/views/produce/schedulePlan/month/produceLineDetailSelectDlg.vue";
import {
  getProcedures,
  getBottleneckProcedure
} from "@/api/produce/schedulePlan/ProduceOrderProductPlanApi";
import schedulemonthdetailson from "@/views/produce/schedulePlan/month/scheduleMonthDetailSon.vue";
import producelineresourcesetdlg from "@/views/produce/schedulePlan/month/produceLineResourceSetDlg.vue";
import { getMonthWorkhours } from "@/api/produce/ProduceCalendarApi";
import { initDeviceResource } from "@/api/produce/schedulePlan/ProduceLinePlanResourceApi";
import moment from "moment";


export default {
  components: {
    Pagination,
    producelinedetailselectdlg,
    schedulemonthdetailson,
    producelineresourcesetdlg
  },
  data() {
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "SaleOrderMst"
      },
      list: null,
      list2: null,
      listLoading: true,
      total: 0,
      total2: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentSaleOrderMstId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      lstSelected: [],
      queryConditions: {
        produceYear: 0,
        produceMonth: 0,
        produceMonthStr: "",
        currentProduceLineId: 0, //当前产线
        currentProduceLineNo: "",
        currentProduceLineName: "",
        lstProcedures: [], //所有工序
        currentMontWorkHours: 0, //当前月的工作小时数
        totalPlanAmount: 0 //计划总产量
      },
      dialogProduceLineVisible: false, //产线选择框
      lstYears: [
        { label: "请选择", value: 0 },
        { label: "2021", value: 2021 },
        { label: "2022", value: 2022 },
        { label: "2023", value: 2023 }
      ],
      lstMonths: [
        { label: "请选择", value: 0 },
        { label: "W01-W04(一月)", value: 1 },
        { label: "W05-W08(二月)", value: 2 },
        { label: "W09-W12(三月)", value: 3 },
        { label: "W13-W16(四月)", value: 4 },
        { label: "W17-W20(五月)", value: 5 },
        { label: "W21-W24(六月)", value: 6 },
        { label: "W25-W28(七月)", value: 7 },
        { label: "W29-W32(八月)", value: 8 },
        { label: "W33-W36(九月)", value: 9 },
        { label: "W37-W40(十月)", value: 10 },
        { label: "W41-W44(十一月)", value: 11 },
        { label: "W45-W48(十二月)", value: 12 }
      ],

      ddBottleneckProcedure: [], //瓶颈工序
      resourceSetDlgVisible: false, //资源配置对话框
      chart:{}, //echart
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  computed: {
    //获取工序按钮颜色，0-30 为浅蓝色;50-80为绿色;80-110为浅红色;110以上为红色
    getBadgeButtonColor() {
      return function(factor, itm) {
        if (itm != null) {
          let s = new String(itm.usedDeviceLoadFactor);
          s = s.substring(0, s.length - 1);
          let f = parseInt(s);
          if (s > 0 && s < 30) {
            return "primary";
          } else if (s >= 30 && s < 70) {
            return "success";
          } else if (s >= 80 && s < 110) {
            return "warning";
          } else if (s >= 110) {
            return "danger";
          } else {
            return "info";
          }
        }
        return "info";
      };
    }
  },
  created() {},
  mounted() {
    //默认选择为当前年份和当前月
    this.queryConditions.produceYear = moment().year();
    this.queryConditions.produceMonth = moment().month();
    let itm = this.lstMonths.find(v => v.value == moment().month());
    if (itm != null) {
      this.queryConditions.produceMonthStr = itm.label;
    }
    //获取当前月的工作时长以计算负荷率
    if (
      this.queryConditions.produceYear != 0 &&
      this.queryConditions.produceMonth != 0
    ) {
      this.getMonthWorkhours();
    }
    //echart
    this.initCharts();
  },
  methods: {
    /**
     * 子组件关闭时通知父组件
     */
    hideProduceLineDlg(e) {
      this.dialogProduceLineVisible = e;
    },
    //切换产线
    changeProduceLine() {
      this.dialogProduceLineVisible = true;
    },
    fetchData() {
      this.getProcedures(this.queryConditions.currentProduceLineId);
    },
    /**获取产线的所有工序 */
    getProcedures(produceLineId) {
      let params = { produceLineId: produceLineId };
      getProcedures(params).then(response => {
        this.queryConditions.lstProcedures = response.data;
        this.queryConditions.lstProcedures.splice(0, 0, {
          id: 0,
          procedureName: "请选择"
        });
        if (
          this.queryConditions.lstProcedures != null &&
          this.queryConditions.lstProcedures.length > 0
        ) {
          this.queryConditions.lstProcedures.forEach(v => {
            v.usedDeviceLoadFactor = 0;
          });
        }
      });
    },
    /**分配资源 */
    allocateResource() {
      if (
        this.queryConditions.currentProduceLineId > 0 &&
        this.queryConditions.lstProcedures != null &&
        this.queryConditions.lstProcedures.length > 0
      ) {
        let params = {
          produceLineId: this.queryConditions.currentProduceLineId,
          produceLineNo: this.queryConditions.currentProduceLineNo,
          mesProcedures: this.queryConditions.lstProcedures
            .filter(v => v.id != null && v.id > 0)
            .map(v => {
              return v.id;
            }),
          produceYear: this.queryConditions.produceYear,
          produceMonth: this.queryConditions.produceMonth
        };
        initDeviceResource(params).then(response => {
          this.resourceSetDlgVisible = true;
        });
      } else {
        this.$message.error("请先选择一条产线并且确定产线至少有一个工序!");
        this.resourceSetDlgVisible = false;
      }
    },
    hideResourceDlg() {
      this.resourceSetDlgVisible = false;
    },
    refreshProduceLine(val) {
      this.queryConditions.currentProduceLineId = val.produceLineId;
      this.queryConditions.currentProduceLineNo = val.produceLineNo;
      this.queryConditions.currentProduceLineName = val.produceLineName;
      this.fetchData();
    },
    handleYearChange(val) {
      this.queryConditions.produceYear = val;
      this.queryConditions.produceYearStr = val;
      if (val != 0) {
        this.getMonthWorkhours();
      }
    },
    handleMonthChange(val) {
      this.queryConditions.produceMonth = val;
      let itm = this.lstMonths.find(v => v.value == val);
      if (itm != null) {
        this.queryConditions.produceMonthStr = itm.label;
      }
      if (val != 0) {
        this.getMonthWorkhours();
      }
    },
    getMonthWorkhours() {
      /**1007 为标准公祖日历的Id 为了测试暂且硬编码*/
      let currentDate =
        this.queryConditions.produceYear +
        "-" +
        this.queryConditions.produceMonth +
        "-01";
      let params = { id: 1008, date: currentDate };
      getMonthWorkhours(params).then(response => {
        this.queryConditions.currentMontWorkHours = response.data;
      });
    },
    changeTotalPlanAmount(val) {
      this.queryConditions.totalPlanAmount = val;
    },

    //更新设备负荷率
    updateFactor(e) {
      if (e == null || e.length <= 0) return;
      this.queryConditions.lstProcedures.forEach(v => {
        let itm = e.find(o => o.procedureId == v.id);
        if (itm != null) {
          v.usedDeviceLoadFactor =
            parseFloat(itm.usedDeviceLoadFactor) * 100 + "%";
        }
      });

      //更新图表
      this.setOptions()
    },

    initCharts() {
      this.chart = this.$echarts.init(document.getElementById("chartProduce"));
      this.setOptions();
    },
    setOptions() {
      let xAxis = this.queryConditions.lstProcedures.filter(v=>v.id>0).map(v=>{
        return v.procedureName;
      }) 
       let xAxisData = this.queryConditions.lstProcedures.filter(v=>v.id>0).map(v=>{
           let s = new String(v.usedDeviceLoadFactor);
          s = s.substring(0, s.length - 1);
        return parseFloat(100/parseInt(s)).toFixed(2);
      }) 
      this.chart.setOption({
        title: {
          text: "工序产能占比"
        },
        tooltip: {},
        xAxis: {
         // data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
          data:xAxis
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "bar",
            //data: [5, 20, 36, 10, 10, 20],
             data:xAxisData
          }
        ]
      });
    }
  }
};
</script>
<style scoped>
.wrapperSon {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.el-badge__content .is-fixed {
  background-color: darkgreen;
}
.main_container {
  width: 100%;
  height: 200px;
  overflow: hidden;
}
</style>
